<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>授权生成器 - 管理员专用</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 600px;
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
            text-align: center;
        }

        .subtitle {
            color: #666;
            text-align: center;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        input, select, textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 14px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        button:active {
            transform: translateY(0);
        }

        .result-box {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed #dee2e6;
            display: none;
        }

        .result-box.show {
            display: block;
            animation: fadeIn 0.5s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .license-key {
            font-family: 'Courier New', monospace;
            font-size: 14px;
            background: white;
            padding: 15px;
            border-radius: 5px;
            word-break: break-all;
            margin: 10px 0;
            border: 1px solid #dee2e6;
        }

        .success-message {
            color: #28a745;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: auto 1fr;
            gap: 10px;
            margin-top: 15px;
            font-size: 14px;
        }

        .info-label {
            font-weight: 600;
            color: #666;
        }

        .info-value {
            color: #333;
        }

        .button-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 15px;
        }

        .secondary-button {
            background: #6c757d;
        }

        .secondary-button:hover {
            box-shadow: 0 10px 20px rgba(108, 117, 125, 0.3);
        }

        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #28a745;
            margin-right: 8px;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(40, 167, 69, 0); }
            100% { box-shadow: 0 0 0 0 rgba(40, 167, 69, 0); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 授权生成器</h1>
        <p class="subtitle">
            <span class="status-indicator"></span>
            使用真实 RSA 2048位加密
            <span style="opacity: 0.7; font-style: italic; margin-left: 5px;">by Chaxi</span>
        </p>

        <!-- 服务器配置 -->
        <div style="background: #f0f8ff; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
            <div class="form-group" style="margin-bottom: 10px;">
                <label for="serverUrl">远程服务器地址（可选）</label>
                <input type="text" id="serverUrl" placeholder="例如: http://your-server.com:3000" 
                       value="" style="background: white;">
                <small style="color: #666; display: block; margin-top: 5px;">
                    留空使用本地模式，填写后将连接远程服务器
                </small>
            </div>
            <button onclick="testServerConnection()" style="padding: 8px 16px; font-size: 14px;">
                🔍 测试连接
            </button>
            <span id="connectionStatus" style="margin-left: 10px; font-size: 14px;"></span>
        </div>

        <div class="form-group">
            <label for="customerName">客户名称</label>
            <input type="text" id="customerName" placeholder="输入客户名称（可选）">
        </div>

        <div class="form-group">
            <label for="machineId">机器标识 *</label>
            <input type="text" id="machineId" placeholder="输入目标机器的硬件ID" required>
            <small style="color: #666; margin-top: 5px; display: block;">
                提示：用户可以在授权验证器中获取机器ID
            </small>
        </div>

        <div class="row">
            <div class="form-group">
                <label for="licenseType">授权类型</label>
                <select id="licenseType">
                    <option value="trial">试用版 (30天)</option>
                    <option value="standard" selected>标准版 (365天)</option>
                    <option value="enterprise">企业版 (永久)</option>
                    <option value="custom">自定义</option>
                </select>
            </div>

            <div class="form-group">
                <label for="duration">自定义时长</label>
                <input type="number" id="duration" placeholder="仅自定义类型" disabled>
            </div>
        </div>

        <div class="row" id="customTimeRow" style="display: none;">
            <div class="form-group">
                <label for="timeUnit">时间单位</label>
                <select id="timeUnit">
                    <option value="days" selected>天</option>
                    <option value="weeks">周</option>
                    <option value="months">月</option>
                    <option value="years">年</option>
                </select>
            </div>
            <div class="form-group">
                <!-- 占位 -->
            </div>
        </div>

        <div class="form-group">
            <label for="features">功能权限</label>
            <select id="features" multiple style="height: 80px;">
                <option value="basic" selected>基础功能</option>
                <option value="advanced">高级功能</option>
                <option value="premium">专业功能</option>
                <option value="all">所有功能</option>
            </select>
            <small style="color: #666; margin-top: 5px; display: block;">
                按住 Ctrl 可多选
            </small>
        </div>

        <button onclick="generateLicense()">🚀 生成授权码</button>

        <div id="resultBox" class="result-box">
            <div class="success-message">✅ 授权码生成成功！</div>
            
            <div class="license-key" id="licenseKey"></div>
            
            <div class="info-grid">
                <span class="info-label">授权ID:</span>
                <span class="info-value" id="licenseId"></span>
                
                <span class="info-label">类型:</span>
                <span class="info-value" id="licenseTypeDisplay"></span>
                
                <span class="info-label">生成时间:</span>
                <span class="info-value" id="issueDate"></span>
                
                <span class="info-label">过期时间:</span>
                <span class="info-value" id="expiryDate"></span>
                
                <span class="info-label">机器ID:</span>
                <span class="info-value" id="machineIdDisplay"></span>
            </div>

            <div class="button-group">
                <button onclick="copyToClipboard()">📋 复制授权码</button>
                <button onclick="saveLicense()" class="secondary-button">💾 保存到文件</button>
            </div>
        </div>
    </div>

    <script>
        const { ipcRenderer } = require('electron');
        let currentLicense = null;
        let useRemoteServer = false;
        let remoteServerUrl = '';

        // 加载保存的服务器地址
        window.addEventListener('DOMContentLoaded', function() {
            const savedServerUrl = localStorage.getItem('remoteServerUrl');
            if (savedServerUrl) {
                document.getElementById('serverUrl').value = savedServerUrl;
            }
        });

        // 测试服务器连接
        async function testServerConnection() {
            const serverUrl = document.getElementById('serverUrl').value.trim();
            const statusElement = document.getElementById('connectionStatus');
            
            if (!serverUrl) {
                statusElement.innerHTML = '<span style="color: #666;">✓ 使用本地模式</span>';
                useRemoteServer = false;
                return;
            }
            
            statusElement.innerHTML = '<span style="color: #007bff;">连接中...</span>';
            
            try {
                const response = await fetch(`${serverUrl}/api/stats`);
                if (response.ok) {
                    statusElement.innerHTML = '<span style="color: #28a745;">✓ 连接成功</span>';
                    useRemoteServer = true;
                    remoteServerUrl = serverUrl;
                    localStorage.setItem('remoteServerUrl', serverUrl);
                } else {
                    statusElement.innerHTML = '<span style="color: #dc3545;">✗ 连接失败</span>';
                    useRemoteServer = false;
                }
            } catch (error) {
                statusElement.innerHTML = '<span style="color: #dc3545;">✗ 无法连接</span>';
                useRemoteServer = false;
            }
        }

        // 监听授权类型变化
        document.getElementById('licenseType').addEventListener('change', function(e) {
            const durationInput = document.getElementById('duration');
            const customTimeRow = document.getElementById('customTimeRow');
            
            if (e.target.value === 'custom') {
                durationInput.disabled = false;
                durationInput.value = 30;
                customTimeRow.style.display = 'grid';
            } else {
                durationInput.disabled = true;
                durationInput.value = '';
                customTimeRow.style.display = 'none';
            }
        });

        // 添加右键菜单支持 (现代Electron方式)
        document.addEventListener('DOMContentLoaded', function() {
            // 为所有输入框添加右键菜单
            document.querySelectorAll('input, textarea, select').forEach(input => {
                input.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    ipcRenderer.send('show-context-menu', 'input');
                });
            });
            
            // 为结果区域添加右键菜单
            document.getElementById('resultBox').addEventListener('contextmenu', function(e) {
                e.preventDefault();
                ipcRenderer.send('show-context-menu', 'general');
            });
            
            // 为其他元素添加右键菜单
            document.addEventListener('contextmenu', function(e) {
                if (!e.target.closest('input, textarea, select, #resultBox')) {
                    e.preventDefault();
                    ipcRenderer.send('show-context-menu', 'general');
                }
            });
        });

        async function generateLicense() {
            const customerName = document.getElementById('customerName').value;
            const machineId = document.getElementById('machineId').value;
            const licenseType = document.getElementById('licenseType').value;
            const duration = document.getElementById('duration').value;
            const featuresSelect = document.getElementById('features');
            
            if (!machineId) {
                alert('请输入机器标识！');
                return;
            }

            // 获取选中的功能
            const features = Array.from(featuresSelect.selectedOptions).map(option => option.value);

            // 准备授权选项
            const options = {
                type: licenseType,
                machineId: machineId,
                customerName: customerName || '未指定',
                features: features || ['basic']
            };

            // 根据类型设置正确的持续时间
            if (licenseType === 'trial') {
                options.duration = 30;
                options.unit = 'days';
            } else if (licenseType === 'standard') {
                options.duration = 365;
                options.unit = 'days';
            } else if (licenseType === 'enterprise') {
                options.duration = 36500; // 约100年，实际上是永久
                options.unit = 'days';
            } else if (licenseType === 'custom' && duration) {
                // 如果是自定义类型，添加时长和单位
                const timeUnit = document.getElementById('timeUnit').value;
                options.duration = parseInt(duration);
                options.unit = timeUnit;
            }

            console.log(`生成授权: 类型=${licenseType}, 持续时间=${options.duration} ${options.unit || '未指定'}`);

            try {
                // 获取系统信息 - 先获取本地系统信息以便本地生成
                const systemInfo = await ipcRenderer.invoke('get-system-info');
                options.systemInfo = systemInfo;
                options.metadata = {
                    customerName: customerName || '未指定'
                };
                
                let result;
                // 检查是否使用远程服务器
                const serverUrl = document.getElementById('serverUrl').value.trim();
                
                if (serverUrl && useRemoteServer) {
                    try {
                        // 设置超时
                        const controller = new AbortController();
                        const timeoutId = setTimeout(() => controller.abort(), 5000);
                        
                        // 使用远程服务器
                        const response = await fetch(`${serverUrl}/api/generate-license`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(options),
                            signal: controller.signal
                        });
                        
                        clearTimeout(timeoutId);
                        
                        if (!response.ok) {
                            throw new Error(`服务器响应错误: ${response.status}`);
                        }
                        
                        const data = await response.json();
                        if (data.success) {
                            result = data;
                        } else {
                            throw new Error(data.error || '远程服务器生成失败');
                        }
                    } catch (serverError) {
                        console.error('远程服务器请求失败:', serverError);
                        // 回退到本地生成，不抛出错误
                        console.log('回退到本地生成模式');
                        result = await ipcRenderer.invoke('generate-license', options);
                    }
                } else {
                    // 使用本地生成
                    console.log('使用本地生成模式');
                    result = await ipcRenderer.invoke('generate-license', options);
                }

                if (result && result.success) {
                    currentLicense = result.data;
                    displayLicense(result.data);
                } else if (result) {
                    alert('生成失败: ' + (result.error || '未知错误'));
                } else {
                    alert('生成失败: 获取结果为空');
                }
            } catch (error) {
                console.error('生成授权码错误:', error);
                alert('生成失败: ' + error.message);
            }
        }

        function displayLicense(license) {
            // 显示结果区域
            document.getElementById('resultBox').classList.add('show');
            
            // 显示授权码
            document.getElementById('licenseKey').textContent = license.formattedKey;
            
            // 显示详细信息
            document.getElementById('licenseId').textContent = license.licenseInfo.id;
            document.getElementById('licenseTypeDisplay').textContent = 
                license.licenseInfo.type.charAt(0).toUpperCase() + license.licenseInfo.type.slice(1);
            document.getElementById('issueDate').textContent = 
                new Date(license.licenseInfo.issueDate).toLocaleString('zh-CN');
            document.getElementById('expiryDate').textContent = 
                new Date(license.licenseInfo.expiryDate).toLocaleString('zh-CN');
            document.getElementById('machineIdDisplay').textContent = 
                license.licenseInfo.machineId.substring(0, 20) + '...';
        }

        function copyToClipboard() {
            if (!currentLicense) return;
            
            navigator.clipboard.writeText(currentLicense.licenseKey).then(() => {
                alert('授权码已复制到剪贴板！');
            });
        }

        async function saveLicense() {
            if (!currentLicense) return;
            
            const saveData = {
                id: currentLicense.licenseInfo.id,
                type: currentLicense.licenseInfo.type,
                customerName: currentLicense.licenseInfo.metadata.customerName,
                machineId: currentLicense.licenseInfo.machineId,
                expiryDate: currentLicense.licenseInfo.expiryDate,
                licenseKey: currentLicense.formattedKey
            };
            
            const result = await ipcRenderer.invoke('save-license', saveData);
            
            if (result.success) {
                alert(`授权文件已保存到:\n${result.path}`);
            }
        }
    </script>
</body>
</html>
